package controller

import (
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sno"
	"github.com/gin-gonic/gin"
)

func init() {
	sgin.AddRouter(FileController{})
}

type FileController struct {
}

// 文件上传
// @Router [post] [/file/upload]
func (m FileController) Upload(c *gin.Context) any {
	filename := c.PostForm("filename")
	for _, v := range strings.Split(filename, ",") {
		os.Remove(v)
	}
	file, err := c.FormFile("file")
	var filePath string
	if err != nil {
		return model.NewFailDefault("获取数据失败")
	} else {
		extstring := path.Ext(file.Filename)
		fileName := sno.GetString() + extstring
		dir := "extlib/template"
		os.MkdirAll(dir, 0666)
		filePath = filepath.Join(dir, "/", fileName)
		c.SaveUploadedFile(file, filePath)
	}
	return model.NewOK(filePath)
}

// 文件下载
// @Router [post] [/file/download]
func (m FileController) Download(c *gin.Context) {
	filename := c.Query("filename")
	name := c.Query("name")
	ext := path.Ext(filename)

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename="+name+ext)
	c.File(filename)
}
